package com.shf.runner;

import com.shf.domain.entity.Article;
import com.shf.mapper.ArticleMapper;
import com.shf.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 将数据库的文章浏览量 放到redis中，使用 预加载方式
 * @author 叶枫
 * @date 2023/11/12.
 */

@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private RedisCache redisCache;
    /**注入 Article持久层*/
    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public void run(String... args) throws Exception {
        //获取所有文章
        List<Article> articleList = articleMapper.selectList(null);
        //拿到我们需要的字段  articleId 和 viewCount
        Map<String, Integer> collect = articleList.stream()
                .collect(Collectors.toMap(new Function<Article, String>() {
                    @Override
                    public String apply(Article article) {
                        return article.getId().toString();


                    }
                }, new Function<Article, Integer>() {
                    @Override
                    public Integer apply(Article article) {

                        return article.getViewCount().intValue();
                    }
                }));
                //将map集合存入 redis中
                redisCache.setCacheMap("viewCount",collect);





    }
}
